package com.xu.tools.util;

import com.xu.tools.annotation.Desensitization;
import com.xu.tools.enums.SensitiveEnum;

import java.lang.reflect.Field;

/**
 * @author xuguan
 * @date 2023/3/12
 * @desc 对象数据脱敏
 */
public class DesensitizationUtil {

    public static Object desensitizationBean(Object obj) throws Exception {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Desensitization desensitization = field.getAnnotation(Desensitization.class);
            if (field.getType() == String.class && desensitization != null) {
                SensitiveEnum type = desensitization.type();
                if (type == SensitiveEnum.NAME) {
                    String source = (String) field.get(obj);
                    String target = source.replaceAll("([\\w\\u4e00-\\u9fa5])([\\w\\u4e00-\\u9fa5])*", "$1*");
                    field.set(obj, target);
                }
                if (type == SensitiveEnum.PASSWORD) {
                    String source = (String) field.get(obj);
                    String target = source.replaceAll("(\\w)(\\w)*(\\w)", "$1*****$3");
                    field.set(obj, target);
                }
                if (type == SensitiveEnum.PHONE) {
                    String source = (String) field.get(obj);
                    String target = source.replaceAll("(\\d{3})(\\d*)(\\d{4})", "$1****$3");
                    field.set(obj, target);
                }
                if (type == SensitiveEnum.EMAIL) {
                    String source = (String) field.get(obj);
                    String target = source.replaceAll("(\\w{3})(\\w*)@(\\w+)", "$1*****$3");
                    field.set(obj, target);
                }
                if (type == SensitiveEnum.ID_NO) {
                    String source = (String) field.get(obj);
                    String target = source.replaceAll("(\\d{3})(\\d+)(\\d{4})", "$1*****$3");
                    field.set(obj, target);
                }
                if (type == SensitiveEnum.ACCOUNT_NO) {
                    String source = (String) field.get(obj);
                    String target = source.replaceAll("(\\d{4})(\\d+)(\\d{6})", "$1*****$3");
                    field.set(obj, target);
                }
            }
        }
        return obj;
    }
}
